package com.w3cnet.leetcode.controller;

import com.w3cnet.leetcode.utils.RsaUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

@RequestMapping(value = "/test")
@RestController
public class TestController {
    @PostMapping("/rsa/encrypt")
    public String encrypt(HttpServletRequest request) throws Exception {
        String text = request.getParameter("text");
        if (text == null) text = "";

        String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvbQwudsfOeadYd9Cx+7VrHL0h/sPdDMiJ6kPGe4WOwBVV+47oA3rjXoFeKFF/BF/mGDSN+qHOaTd1v4MHT6RIzpXCBJ62YC2pK8kwr9yED4CE+JQfK5Xu98uaPtG7HESiGGIqlk9xh3IOz6/v/lEZnK6YZ4GQ00SXwrtfP6L27kf7PjXJjfMSlxq9Z/Cf76uHE+9H9NlhG0UBxtQ0yo+rFE9wYDcVxSrAQKwZxAzuB46zyRaDaKnXPj3RnZgde3VU0kpnNHl+wfEVZ6liZHZCdsfKZ+y4Tl4gsU25WnPWyUxHOMWl31mCzTnIHVJOJq4hbqcKocIeT51S1zXe3aBdQIDAQAB";
        return RsaUtil.encrypt(text, publicKey, "UTF-8");
    }

    @PostMapping("/rsa/decrypt")
    public String decrypt(HttpServletRequest request) throws Exception {
        String ciphertext = request.getParameter("ciphertext");
        if (ciphertext == null) ciphertext = "";

        String privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC9tDC52x855p1h30LH7tWscvSH+w90MyInqQ8Z7hY7AFVX7jugDeuNegV4oUX8EX+YYNI36oc5pN3W/gwdPpEjOlcIEnrZgLakryTCv3IQPgIT4lB8rle73y5o+0bscRKIYYiqWT3GHcg7Pr+/+URmcrphngZDTRJfCu18/ovbuR/s+NcmN8xKXGr1n8J/vq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ZKTqqhcjwVSLTb05uXKHTip2WtlxS/jzusrBWBDdgbBPko0iFNiRz2FqSi4d1ybzsBkWe5TdsLbGzzWv+J3oyQ6plxmhRzwglBKLa7gqGTOy9l0+WNu2IOyhhWoSo/EME5fAnAoGANaK1cTWmXer+nq861KO9REpG1XpNgS1t46Xt+BPe1Q19hL/8K11Xljf5DjLHOe0UrQn12x5EHLqNm3K6ZgjLjYrdS21xPSqMQ+fU+/1Wfvz0nvkqBcmhWYCY4RmdU9lljy4wWcQDAQfOsTw91SF2KOuRp7Bp1c445Ebe33VyThI=";
        return RsaUtil.decrypt(ciphertext, privateKey, "UTF-8");
    }

    @GetMapping("/rsa/key")
    public Map<Integer, String> getKey() throws NoSuchAlgorithmException {
        //生成公钥和私钥
        return RsaUtil.genKeyPair();
    }
}
